package com.lyjilu.web.servlet;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.Blob;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.lyjilu.util.DaoUtil;

/**
 * Servlet implementation class DownloadSvt
 */
@WebServlet("/DownloadSvt")
public class DownloadSvt extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public DownloadSvt() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		this.doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String id = request.getParameter("id");
		String sql = "select f.name,f.content,f.size from file f where id = ?";
		Connection conn = null;
		Map<String, Object> list = null;
		try {
			conn = DaoUtil.getConn();
			list = DaoUtil.find(conn, sql, id);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			DaoUtil.closeDao(null, null, conn);
		}
		List<String> metaName = (List<String>) list.get(DaoUtil.METADATANAME);
		List<Map<String, Object>> dblist = (List<Map<String, Object>>) list
				.get(DaoUtil.DBDATANAME);
		Blob fileContent = (Blob) dblist.get(0).get("content");
		String fileName = (String) dblist.get(0).get("name");
		String fileSize = (String) dblist.get(0).get("size");
		response.setContentType("application/octet-stream");
		response.addHeader("Content-Disposition", "attachment;filename="
				+ new String(fileName.getBytes(), "UTF-8"));
		response.addHeader("Content-Length", "" + fileSize);
		OutputStream out = response.getOutputStream();
		InputStream input = null;
		try {
			input = fileContent.getBinaryStream();
			byte[] b = new byte[10240];
			int i = 0;
			while ((i = input.read(b)) != -1)
				out.write(b, 0, i);
			out.flush();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			out.flush();
			out.close();
			input.close();
		}
	}

}
